 package com.itbour.web.action.trade;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.itbour.com.page.Page;
import com.itbour.common.base.BaseAction;
import com.itbour.common.util.StringUtils;
import com.itbour.dto.com.IdNameDto;
import com.itbour.dto.com.UserInfoDto;
import com.itbour.dto.tg.OrgInfoDto;
import com.itbour.dto.trade.CouponInfoDto;
import com.itbour.dto.trade.InvoiceInfoDto;
import com.itbour.dto.trade.PartnerInfoDto;
import com.itbour.service.trade.CouponService;
import com.opensymphony.xwork2.ActionContext;

/**
 * copyright Itbour team 2016
 * 
 * @author abby
 */

public class GetCouponWebAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private CouponService couponService;
	private String delIds;
	
	// [商品]
	private HashMap<String, Object> couponMapResult = new HashMap<String, Object>();//[分页]商品信息列表
	private List<CouponInfoDto> couponInfoList;		// 商品信息列表
	private CouponInfoDto couponInfo;				// 更新用
	private String cId;								// 优惠券id
	private List<OrgInfoDto> orgComboList;	        // 优惠券持有组织者
	private List<IdNameDto> ownerComboList;	        // 优惠券拥有人
	private List<IdNameDto> lotNoComboList;			// 批次号
	
	private String findYhType;						//检索条件[优惠券类型]
	private String findYhState;						//检索条件[状态]
	private String findYhUse;						//检索条件[用途]
	private String findYhLimit;						//检索条件[限制]
	private String findYhLot;						//检索条件[批次]
	private String findYhCode;						//检索条件[优惠券码]
	private String findYhOrg;						//检索条件[所有组织]
	private String findYhOwner;						//检索条件[所有者]
	private String findExpDateStart;				// 检索条件[优惠券有效时间范围(起始)]
	private String findExpDateEnd;					// 检索条件[优惠券有效时间范围(截止)]
	private String findCodeId;						// 优惠券ID
	
	
	private String findPubFlg;// 检索条件[发布状态]
	private String ids;// 通用ids[逗号连接]
	private String order;// 显示顺序
	private String findConverUserId;// 兑换人用户ID
	
	// 分页获取商品信息
	public String getCouponInfoPg() throws Exception {
		// 用户信息
		Map<String, Object> session = ActionContext.getContext().getSession();
    	UserInfoDto user = (UserInfoDto)session.get("user");
    	
		HttpServletRequest request = ServletActionContext.getRequest();
		String pageNumber = request.getParameter("page");
		String pageSize = request.getParameter("rows");
		
		Map<String, Object> param = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(findYhCode)) {
			param.put("c_code", "%"+findYhCode+"%");
		}
		if (StringUtils.isNotEmpty(findYhOrg)) {
			param.put("org_id", findYhOrg);
		}
		if (StringUtils.isNotEmpty(findYhOwner)) {
			param.put("owner", findYhOwner);
		}
		if (StringUtils.isNotEmpty(findYhLot)) {
			param.put("lot_no", findYhLot);
		}
		if (StringUtils.isNotEmpty(findYhType)) {
			param.put("type", findYhType);
		}
		if (StringUtils.isNotEmpty(findYhUse)) {
			param.put("use", findYhUse);
		}
		if (StringUtils.isNotEmpty(findYhLimit)) {
			param.put("limit_type", findYhLimit);
		}
		if (StringUtils.isNotEmpty(findYhState)) {
			param.put("state", findYhState);
		}
		if (StringUtils.isNotBlank(findExpDateStart)) {
			param.put("expDateStart", findExpDateStart);
		}
		if (StringUtils.isNotBlank(findExpDateEnd)) {
			param.put("expDateEnd", findExpDateEnd);
		}
		if (StringUtils.isNotEmpty(findConverUserId)){
			param.put("user_id",findConverUserId);
		}
		if (StringUtils.isNotEmpty(findCodeId)){
			param.put("c_id", findCodeId);
		}
		Page page = couponService.couponPgQuery(param,
				Integer.parseInt(pageNumber),
				Integer.parseInt(pageSize));
		HashMap<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("total", page.getTotalCount());
		resMap.put("rows", page.getResult());
		//writeJSON(resMap);
		couponMapResult = resMap;
		return SUCCESS;
	}
	
	// 获取 信息列表
	public String getCouponInfoLst() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		Map<String, Object> param = new HashMap<String, Object>();
		String id = request.getParameter("c_id");
		if (StringUtils.isNotEmpty(id)) {
			param.put("c_id", id);
		}
		couponInfoList = couponService.selectCouponInfo(param);
		return SUCCESS;
	}
		
	
	// 新建优惠券
	public void addCoupon() throws Exception {
		if (couponInfo != null && couponInfo.getProcMode()==1) {
			// 新建并发放优惠券
			addAndGrantCoupon();
			return;
		}
		
		if (couponInfo != null && couponInfo.getGenCnt()>0) {
			Map<String, Object> session = ActionContext.getContext().getSession();
	    	UserInfoDto user = (UserInfoDto)session.get("user");
	    	if (user != null) {
	    		couponInfo.setUpdate_by(user.getUser_id().toString());
	    	}
	    	
	    	Date date = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			String lotNo = format.format(date);
			
			couponInfo.setLot_no(lotNo);// 批次号
			couponInfo.setState(10);// 新建
	    	
	    	for(int i=0; i<couponInfo.getGenCnt(); i++) {
	    		couponInfo.setC_code(genCouponCode(lotNo, i+1));
	    		couponService.addCoupon(couponInfo);
	    	}
	    	
	    	this.writeJSON("ok");
    		
		} else {
			this.writeJSON("ng");
		}
	}
	
	// 生成优惠码
	// strTime: yyyyMMddHHmmss
	// idx: 1~999
	private String genCouponCode(String strTime, int idx){
		long rd = (long)(Math.random()*100);
		long p1 = rd*10000000 + Long.valueOf(strTime.substring(10))*1000+idx;
		String strP1 = Long.toString(p1, 36).toUpperCase();
		while (strP1.length()<6){
			strP1 = "0"+strP1;
		}
		
		int Y = Integer.valueOf(strTime.substring(2, 4));// TODO
		int M = Integer.valueOf(strTime.substring(4, 6));
		int D = Integer.valueOf(strTime.substring(6, 8));
		int H = Integer.valueOf(strTime.substring(8, 10));
		if(D>25){
			M += 12;
			D -= 25;
		}
		String strP2 = toRadix26(Y)+toRadix26(M)+toRadix26(D)+toRadix26(H);
		
		return strP1+strP2;
	}
	
	private String toRadix26(int num){
		String arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		return arr.charAt(num)+"";
	}
		
	// 更新价格信息列表
	public void updCoupon() throws Exception {
		if (couponInfo != null && 
			((couponInfo.getC_id() != null && couponInfo.getC_id()>0))) {
			Map<String, Object> session = ActionContext.getContext().getSession();
	    	UserInfoDto user = (UserInfoDto)session.get("user");
	    	
	    	Map<String, Object> param = new HashMap<String, Object>();
	    	
	    	if(couponInfo.getC_id() != null && couponInfo.getC_id()>0){
		    	param.put("c_id", couponInfo.getC_id());
	    	}	 
	    	if(StringUtils.isNotBlank(couponInfo.getIds())){
	    		param.put("ids", StringUtils.listToString2(StringUtils.stringToList2(couponInfo.getIds())));
	    	}
	    	if(user != null) {
	    		param.put("update_by", user.getUser_id());
	    	}
	    	if(couponInfo.getState() != null) {
	    		param.put("state", couponInfo.getState());
	    	}
	    	if(couponInfo.getType() != null ){
		    	param.put("type", couponInfo.getType());
	    	}
	    	if(couponInfo.getUse() != null ){
		    	param.put("use", couponInfo.getUse());
	    	}
	    	if(couponInfo.getC_code() != null) {
	    		param.put("c_code", couponInfo.getC_code());
	    	}
	    	if(couponInfo.getOrg_id() != null) {
	    		param.put("org_id", couponInfo.getOrg_id());
	    	}
	    	if(couponInfo.getOwner() != null) {
	    		param.put("owner", couponInfo.getOwner());
	    	}
	    	if(couponInfo.getDesc() != null) {
	    		param.put("desc", couponInfo.getDesc());
	    	}
	    	if(couponInfo.getState() != null) {
	    		param.put("state", couponInfo.getState());
	    	}
	    	if(couponInfo.getDiscount() != null) {
	    		param.put("discount", couponInfo.getDiscount());
	    	}
	    	if(couponInfo.getMin_order_fee() != null) {
	    		param.put("min_order_fee", couponInfo.getMin_order_fee());
	    	}
	    	if(couponInfo.getExpiry_time() != null) {
	    		param.put("expiry_time", couponInfo.getExpiry_time());
	    	}
	    	if(couponInfo.getLimit_type() != null) {
	    		param.put("limit_type", couponInfo.getLimit_type());
	    	}
	    	couponService.updCoupon(param);
		}
		this.writeJSON("ok");
	}
	
	// 删除信息列表
	public void delCoupon() throws Exception {
		couponService.delCoupon(ids);
		this.writeJSON("ok");
	}
	
	// 发放优惠券
	public void grantCoupon() throws Exception {
		Map<String, Object> session = ActionContext.getContext().getSession();
    	UserInfoDto user = (UserInfoDto)session.get("user");
		if (user != null && user.getUser_id()>0
			&& couponInfo != null
			&& couponInfo.getC_id() != null && couponInfo.getC_id()>0
			&& couponInfo.getUser_id() != null && couponInfo.getUser_id()>0) {
	    	
	    	Map<String, Object> param = new HashMap<String, Object>();
	    	param.put("update_by", user.getUser_id());// 发放者
	    	param.put("c_id", couponInfo.getC_id());// 优惠券id
	    	param.put("user_id", couponInfo.getUser_id());// 指定用户
	    	if(couponInfo.getExpiry_time() != null) {
	    		param.put("expiry_time", couponInfo.getExpiry_time());
	    	}
	    	if(couponInfo.getDesc() != null) {
	    		param.put("desc", couponInfo.getDesc());
	    	}
	    	couponService.grantCoupon(param);
	    	this.writeJSON("ok");
	    	
		} else {
			this.writeJSON("ng");
		}
	}
	
	// 批量发放优惠券
	public void addAndGrantCoupon() throws Exception {
		Map<String, Object> session = ActionContext.getContext().getSession();
    	UserInfoDto user = (UserInfoDto)session.get("user");
		if (user != null && user.getUser_id()>0 && couponInfo != null) {
			
			couponInfo.setUpdate_by(user.getUser_id().toString());
	    	
	    	Date date = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			String lotNo = format.format(date);
			
			couponInfo.setLot_no(lotNo);// 批次号
			couponInfo.setState(15);// 领取!!
			
			List<Long> lstMobile = StringUtils.stringToList2(couponInfo.getPhoneNums());
			//param.put("ids", StringUtils.listToString2(lstMobile));
	    	
	    	for(int i=0; i<lstMobile.size(); i++) {
	    		couponInfo.setC_code(genCouponCode(lotNo, i+1));
	    		couponInfo.setMobile(lstMobile.get(i).toString());
	    		couponService.addCoupon(couponInfo);
	    	}
	    	
	    	// 批量兑换
	    	Map<String, Object> param = new HashMap<String, Object>();
	    	param.put("update_by", user.getUser_id());
	    	param.put("phoneNums", StringUtils.listToString2(lstMobile));
	    	param.put("lot_no", lotNo);
	    	couponService.grantCouponByMobile(param);
	    	
	    	this.writeJSON("ok");
	    	
		} else {
			this.writeJSON("ng");
		}
	}
	
	// 获取批次号
	public String getLotNoForCombo() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String flg = request.getParameter("blkFlg");
		Map<String, Object> param = new HashMap<String, Object>();
		lotNoComboList = couponService.selectLotNoInfo(param);
		if(lotNoComboList != null && lotNoComboList.size()>0){
			// 添加空白项目
			if("1".equals(flg)){
				IdNameDto blankItem = new IdNameDto();
				blankItem.setId("0");
				blankItem.setName("[不限]");
				lotNoComboList.add(0, blankItem);
			}
			
			// 默认选中
			lotNoComboList.get(0).setSelected(true);
		}
		return SUCCESS;
	}
	
	// 获取组织信息
	public String getOrgForCombo() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String flg = request.getParameter("blkFlg");
		Map<String, Object> param = new HashMap<String, Object>();
		orgComboList = couponService.selectOrgInfo(param);
		if(orgComboList != null && orgComboList.size()>0){
			// 添加空白项目
			if("1".equals(flg)){
				OrgInfoDto blankItem = new OrgInfoDto();
				blankItem.setOrg_id(0L);
				blankItem.setName("[不限]");
				orgComboList.add(0, blankItem);
			}
		}
		return SUCCESS;
	}
	// 获取组织用户
	public String getOrgUserForCombo() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String flg = request.getParameter("blkFlg");
		String orgId = request.getParameter("orgId");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("org_id", orgId);
		ownerComboList = couponService.selectOrgUserInfo(param);
		if(ownerComboList != null && ownerComboList.size()>0){
			// 添加空白项目
			if("1".equals(flg)){
				IdNameDto blankItem = new IdNameDto();
				blankItem.setId("0");
				blankItem.setName("[不限]");
				ownerComboList.add(0, blankItem);
			}
			
			// 默认选中第一个
			ownerComboList.get(0).setSelected(true);
		}
		return SUCCESS;
	}
	
	// 导出优惠券信息
	public void downCouponInfo() throws Exception{
		StringBuilder sb = new StringBuilder();
		String SEP = ",";
		
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String dataStr = format.format(date);
		String dataStr2 = format2.format(date);
		
		sb.append("示界港优惠码(券)详情:").append(SEP).append(dataStr).append("\n");
		
		sb.append("券ID")
		.append(SEP).append("批次号")
		.append(SEP).append("兑换码")
		.append(SEP).append("券类型")
		.append(SEP).append("优惠额度")
		.append(SEP).append("持有组织")
		.append(SEP).append("持有者")
		.append(SEP).append("最小订单金额")
		.append(SEP).append("发放时间")
		.append(SEP).append("有效截止日")
		.append(SEP).append("限制范围")
		.append(SEP).append("用途")
		.append(SEP).append("备注")
		.append(SEP).append("状态")
		.append(SEP).append("兑换用户")
		.append(SEP).append("使用时间")
		.append(SEP).append("订单ID")
		.append(SEP).append("更新日期")
		.append("\n");
		
		Map<String, Object> param = new HashMap<String, Object>();
		HttpServletRequest request = ServletActionContext.getRequest();
		String lotNo = request.getParameter("lotNo");
		if(StringUtils.isNotBlank(lotNo)) {
			param.put("lot_no", lotNo);
		}else{
			lotNo = "ALL";
		}
		List<CouponInfoDto> oInfoLst = couponService.selectCouponInfo(param);
		if(oInfoLst!=null && oInfoLst.size()>0) {
			for(int i=0; i<oInfoLst.size(); i++) {
				CouponInfoDto cInfo = oInfoLst.get(i);
				
				String showType = "未知";
	    		switch(cInfo.getType()){
	    			case 10: showType="直接抵扣"; break;
	    			case 20: showType="满减券"; break;
	    			case 30: showType="折扣券"; break;
	    		}
	    		
				String showLimit = "不限";
        		switch(cInfo.getLimit_type().intValue()){
        			case 1: showLimit="海报模版"; break;
        			case 2: showLimit="多页模版"; break;
        			case 3: showLimit="PPT模版"; break;
        			case 4: showLimit="印品"; break;
        			case 9: showLimit="虚拟商品"; break;
        		}
        		
				String showUse = "未知";
				switch (cInfo.getUse()){
					case 10: showUse = "通用"; break;
					case 20: showUse = "app抽奖用"; break;
					case 30: showUse = "合伙人抽奖用[印品]"; break;
					case 31: showUse = "合伙人抽奖用[会员充值]"; break;
					case 40: showUse = "指定发放用"; break;
				}
				
				String showState = "未知";
				switch (cInfo.getState()){
					case 10: showState = "未兑换"; break;
					case 15: showState = "已领取"; break;
					case 20: showState = "已兑换"; break;
					case 30: showState = "已下单"; break;
					case 40: showState = "已使用"; break;
				}
				
				sb.append( "\""+Null2Str(cInfo.getC_id())+"\"" )
				.append(SEP).append( "\""+Null2Str(cInfo.getLot_no())+"\"" )
				.append(SEP).append( "\""+Null2Str(cInfo.getC_code())+"\"" )
				.append(SEP).append( "\""+showType+"\"" )
				.append(SEP).append( "\""+Null2Str(cInfo.getDiscount())+"\"" )
				.append(SEP).append( "\""+Null2Str(cInfo.getOrg_id())+"\"" )
				.append(SEP).append( "\""+Null2Str(cInfo.getOwner())+"\"" )
				.append(SEP).append( "\""+Null2Str(cInfo.getMin_order_fee())+"\"" )
				.append(SEP).append( "\""+Null2Str(cInfo.getIssue_time())+"\"" )
				.append(SEP).append( "\""+Null2Str(cInfo.getExpiry_time())+"\"" )
				.append(SEP).append( "\""+showLimit+"\"" )
				.append(SEP).append( "\""+showUse+"\"" )
				.append(SEP).append( "\""+Null2Str(cInfo.getDesc())+"\"" )
				.append(SEP).append( "\""+showState+"\"" )
				.append(SEP).append( "\""+Null2Str(cInfo.getUser_id())+"\"" )
				.append(SEP).append( "\""+Null2Str(cInfo.getUsed_time())+"\"" )
				.append(SEP).append( "\""+Null2Str(cInfo.getTrade_obj_id())+"\"" )
				.append(SEP).append( "\""+Null2Str(cInfo.getUpdate_time())+"\"" )
				.append("\n");
			}
		}
			
		String fileName = "ITB_COUPON_INFO_"+lotNo+"_"+dataStr2+".csv";
		
        String output = sb.toString();
        HttpServletResponse response = ServletActionContext.getResponse();
        response.addHeader("Content-Disposition", "attachment; filename="+fileName); 
        response.setContentType("application/octet-stream"); 
        response.setCharacterEncoding("UTF8"); 
        response.getWriter().write(output); 
        response.flushBuffer();
	}
	private String Null2Str(Object in){
		return (in==null)?"":String.valueOf(in);
	}
	
	public CouponService getCouponService() {
		return couponService;
	}

	public void setCouponService(CouponService couponService) {
		this.couponService = couponService;
	}

	public HashMap<String, Object> getCouponMapResult() {
		return couponMapResult;
	}

	public void setCouponMapResult(HashMap<String, Object> couponMapResult) {
		this.couponMapResult = couponMapResult;
	}

	public List<CouponInfoDto> getCouponInfoList() {
		return couponInfoList;
	}

	public void setCouponInfoList(List<CouponInfoDto> CouponInfoList) {
		this.couponInfoList = couponInfoList;
	}

	public CouponInfoDto getCouponInfo() {
		return couponInfo;
	}

	public void setCouponInfo(CouponInfoDto couponInfo) {
		this.couponInfo = couponInfo;
	}

	public String getCId() {
		return cId;
	}

	public void setCId(String cId) {
		this.cId = cId;
	}

	public String getFindPubFlg() {
		return findPubFlg;
	}

	public void setFindPubFlg(String findPubFlg) {
		this.findPubFlg = findPubFlg;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}
	
	public String getFindYhType() {
		return findYhType;
	}

	public void setFindYhType(String findYhType) {
		this.findYhType = findYhType;
	}

	public String getFindYhCode() {
		return findYhCode;
	}

	public void setFindYhCode(String findYhCode) {
		this.findYhCode = findYhCode;
	}

	public String getFindYhOrg() {
		return findYhOrg;
	}

	public void setFindYhOrg(String findYhOrg) {
		this.findYhOrg = findYhOrg;
	}

	public String getFindYhOwner() {
		return findYhOwner;
	}

	public void setFindYhOwner(String findYhOwner) {
		this.findYhOwner = findYhOwner;
	}

	public String getDelIds() {
		return delIds;
	}

	public void setDelIds(String delIds) {
		this.delIds = delIds;
	}

	public String getFindExpDateStart() {
		return findExpDateStart;
	}

	public void setFindExpDateStart(String findExpDateStart) {
		this.findExpDateStart = findExpDateStart;
	}

	public String getFindExpDateEnd() {
		return findExpDateEnd;
	}

	public void setFindExpDateEnd(String findExpDateEnd) {
		this.findExpDateEnd = findExpDateEnd;
	}

	public List<IdNameDto> getOwnerComboList() {
		return ownerComboList;
	}

	public void setOwnerComboList(List<IdNameDto> ownerComboList) {
		this.ownerComboList = ownerComboList;
	}

	public String getFindYhState() {
		return findYhState;
	}

	public void setFindYhState(String findYhState) {
		this.findYhState = findYhState;
	}

	public List<IdNameDto> getLotNoComboList() {
		return lotNoComboList;
	}

	public void setLotNoComboList(List<IdNameDto> lotNoComboList) {
		this.lotNoComboList = lotNoComboList;
	}

	public String getFindYhLot() {
		return findYhLot;
	}

	public void setFindYhLot(String findYhLot) {
		this.findYhLot = findYhLot;
	}

	public String getFindYhUse() {
		return findYhUse;
	}

	public void setFindYhUse(String findYhUse) {
		this.findYhUse = findYhUse;
	}

	public List<OrgInfoDto> getOrgComboList() {
		return orgComboList;
	}

	public void setOrgComboList(List<OrgInfoDto> orgComboList) {
		this.orgComboList = orgComboList;
	}

	public String getFindYhLimit() {
		return findYhLimit;
	}

	public void setFindYhLimit(String findYhLimit) {
		this.findYhLimit = findYhLimit;
	}
	public String getFindConverUserId() {
		return findConverUserId;
	}
	public void setFindConverUserId(String findConverUserId) {
		this.findConverUserId = findConverUserId;
	}

	public String getFindCodeId() {
		return findCodeId;
	}

	public void setFindCodeId(String findCodeId) {
		this.findCodeId = findCodeId;
	}
}
